import { createRouter, createWebHashHistory } from 'vue-router';

export const Layout = () => import('@/layout/index.vue');
export const constantRoutes = [
  {
    path: '/login',
    component: () => import('@/view/login/index.vue'),
    meta: { hidden: true }
  },

  {
    path: '/404',
    component: () => import('@/view/errorPage/404.vue'),
    meta: { hidden: true }
  },
  {
    path: '/:pathMatch(.*)*',
    component: () => import('@/view/errorPage/404.vue'),
    meta: { hidden: true }
  },
  {
    path: '/',
    component: Layout,
    redirect: '/dashboard',
    children: [
      {
        path: 'dashboard',
        component: () => import('@/view/dashboard/index.vue'),
        meta: { title: '首页', affix: true }
      },
      {
        path: '401',
        component: () => import('@/view/errorPage/401.vue'),
        meta: { hidden: true }
      }
    ]
  }
];
export const asyncRoutes = [];

// 创建加载异步路由的函数
export function loadAsyncRoutes() {
  return new Promise((resolve) => {
    const modules = import.meta.glob('./modules/*.js');
    const promiseArr = [];

    Object.entries(modules).forEach(([k, v]) => {
      const promiseObj = v().then((m) => {
        asyncRoutes.push(m.default);
      });
      promiseArr.push(promiseObj);
    });
    // 对路由进行排序
    function sortKey(array, key) {
      return array.sort((a, b) => {
        const x = a['meta'] && a['meta'][key] !== undefined ? a['meta'][key] : 0;
        const y = b['meta'] && b['meta'][key] !== undefined ? b['meta'][key] : 0;
        return x < y ? -1 : x > y ? 1 : 0;
      });
    }
    Promise.all(promiseArr).then(() => {
      sortKey(asyncRoutes, 'sortVal');
      resolve();
    });
  });
}

// 添加异步路由到路由器的函数
export function addAsyncRoutes(router) {
  asyncRoutes.forEach(route => {
    router.addRoute(route);
  });
  router.options.routes = [...constantRoutes, ...asyncRoutes];
}

// 创建路由器（初始只包含常量路由）
const router = createRouter({
  history: createWebHashHistory(),
  routes: [...constantRoutes],
  // 刷新时，滚动条位置还原
  scrollBehavior: () => ({ left: 0, top: 0 })
});

export default router;